package org.multimedia.jolitorask.extension.calendar.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

import net.fortuna.ical4j.data.CalendarBuilder;
import net.fortuna.ical4j.data.ParserException;
import net.fortuna.ical4j.filter.Filter;
import net.fortuna.ical4j.filter.PeriodRule;
import net.fortuna.ical4j.model.Calendar;
import net.fortuna.ical4j.model.Component;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Dur;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.component.VEvent;

public class EventParser {
	
	private Calendar calendar;
	private Date startDate;
	private int id;
	
	private Connection c;
	private Statement s;

	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	public EventParser(Connection connexion, int id, URL fichier) {
		
		this.id = id;

		InputStream fin;
		try {
			
			/* Construit le iCalendar */
			fin = fichier.openStream();
			CalendarBuilder builder = new CalendarBuilder();
			calendar = builder.build(fin);
			
			/* Recupere la date du premier jour de la semaine */
			startDate = getStartWeekDate();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserException e) {
			e.printStackTrace();
		}

		try {
	      
			c = connexion; 
			s = c.createStatement();
			  
		}catch( Exception x ) {
		    x.printStackTrace();

		}
			
	}
	
	/**
	 * Parse le iCalendar
	 */
	@SuppressWarnings("unchecked")
	public void parse(){
	
		Period period = new Period(new DateTime(startDate), new Dur(1));
		Filter filter = new Filter(new PeriodRule(period));
		long start, end;

		/* On prend les evenement de la semaine */
		Iterator<Component> eventsOfCurrentWeek = filter.filter(calendar.getComponents(Component.VEVENT)).iterator();
		
		/* Pour tout les evenement */
		while(eventsOfCurrentWeek.hasNext()){
			
			VEvent event = (VEvent)eventsOfCurrentWeek.next();
			
			if( event.getAlarms().size() == 0 ){
			
				if( event.getSummary() != null ){
					
					String phone = event.getSummary().getValue();
				
					Iterator<Period> reccur = event.calculateRecurrenceSet(period).iterator();
					while(reccur.hasNext()){
						
						Period elem = reccur.next();
						start = elem.getStart().getTime();
						end = elem.getEnd().getTime();
						
						//test
						System.out.println(phone+" : "+new Date(start)+" ----> "+new Date(end));
						ajouterEvent( phone, new Date(start), new Date(end) );
					}	
				}
			}
		}
	}
	
	/**
	 * Se place a la premiere seconde de la semaine (Lundi 00h00min00s00)
	 * @return la date du debut de la semaine
	 */
	private Date getStartWeekDate(){
		
		java.util.Calendar cal = java.util.Calendar.getInstance();
		cal.setTime(new Date());
		cal.set(java.util.Calendar.DAY_OF_WEEK, java.util.Calendar.MONDAY);
		cal.set(java.util.Calendar.HOUR_OF_DAY, 0);
		cal.set(java.util.Calendar.MINUTE, 0);
		cal.set(java.util.Calendar.SECOND, 0);
		cal.set(java.util.Calendar.MILLISECOND, 0);
		
		return cal.getTime();
	}

	private void ajouterEvent( String phone, Date start, Date end ){

		/* on recup l id du phone */
		try{
		
			String requete = "SELECT `id_telephone` "+
			" FROM `telephones`, `ical_calendars`"+
			" WHERE `id_calendar` = "+id+
			" AND `ical_calendars`.`utilisateur` = `telephones`.`fk_utilisateur`"+
			" AND `nom` LIKE \""+phone+"\"";

			ResultSet rs = s.executeQuery ( requete );

			if(rs.next()){

				int idTel = rs.getInt("id_telephone");

				s.execute ( "INSERT INTO `ical_events` (`id_event`, `calendar`, `telephone`, `dtstart`, `dtend`) VALUES (NULL, '"+id+"', '"+idTel+"', '"+sdf.format(start)+"', '"+sdf.format(end)+"');" );
		
			}

		}catch( Exception e ) {

			e.printStackTrace();

		}

	}

}
